package com.demo.common.config;

import feign.Client;
import feign.Request;
import feign.Response;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.util.Collection;
import java.util.Map;

/**
 * 自定义 Feign 客户端
 * 主要完成了请求的日志记录
 *
 * @author YT
 * @date 2019-05-13
 */
@Slf4j
public class DemoFeignClient implements Client {

    @Override
    public Response execute(Request request, Request.Options options) throws IOException {
        log.info("execute request method = {}", request.httpMethod());
        log.info("execute request headers");
        Map<String, Collection<String>> headers = request.headers();
        for (Map.Entry<String, Collection<String>> entry : headers.entrySet()) {
            StringBuilder stringBuilder = new StringBuilder();
            for (int j = 0; j < entry.getValue().size(); j++) {
                if (stringBuilder.length() > 0) {
                    stringBuilder.append(",");
                }
                stringBuilder.append(entry.getValue());
            }
            System.out.println(entry.getKey() + ":" + stringBuilder.toString());
        }
        Request.Body body = request.requestBody();
        if (body != null) {
            log.info("execute request body = {}", new String(body.asString()));
        }
        // 使用 Feign 默认的客户端请求
        return new Client.Default(null, null).execute(request, options);
    }
}
